﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using hotel.Win.Common;
using System.Windows.Forms;
namespace hotel.Win.Systems
{
    public class TimingTask
    {
        /// <summary>
        /// 开启自动夜审定时器
        /// </summary>
        public void StartAutoYeShen()
        {
            var t = new System.Timers.Timer(5 * 60 * 1000);//5 * 60 * 1000
            t.Elapsed += new System.Timers.ElapsedEventHandler(ExetuteYeShen);//到达时间的时候执行事件； 
            t.AutoReset = true;//设置是执行一次（false）还是一直执行(true)； 
            t.Enabled = true;
        }
        /// <summary>
        /// 执行夜审
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void ExetuteYeShen(object source, System.Timers.ElapsedEventArgs e)
        {
            //不限制IP
            if ((DateTime.Now >= Convert.ToDateTime(DateTime.Now.Date.ToString("yyyy-MM-dd ") + XTCSModel.GetXTCS.ZDYS_SJ)
                && DateTime.Now.Date> Convert.ToDateTime(XTCSModel.GetXTCS.YYRQ)))
            {
                var timer = (source as System.Timers.Timer);
                using (var _context = MyDataContext.GetDataContext)
                {
                    if (_context.YSJL_Check().First() != 0)
                    {
                        timer.Enabled = false;
                        timer.Interval = 15 * 60 * 1000;//增长轮询时间
                        timer.Enabled = true;
                        return;
                    }
                    timer.Enabled = false;//当对话框弹出式，如果不选择，过一会还会出现一个
                    if (MessageBox.Show("自动夜审时间已到，是否自动夜审?", "夜审提醒", MessageBoxButtons.YesNo) != DialogResult.Yes)
                    {
                        timer.Enabled = true;
                        return;
                    }                        
                    
                    _context.YSJL_Create(UserLoginInfo.FullName, "自动夜审");
                    XTCSModel.GetXTCS.Reset();
                    if (XTCSModel.GetXTCS.SF_ZDBF)
                    {
                        string path = XTCSModel.GetXTCS.BFWJLJ + "hotel" + DateTime.Now.ToString("yyyyMMddHHmm") + ".bak";
                        try
                        {
                            _context.BackUpHotel(path);
                        }
                        catch (Exception ex2)
                        {
                            throw new Exception("自动数据库备份时出错：备份路径=" + path + "\n错误信息" + ex2.Message + "\n请与管理员联系！");
                        }
                    }
                    MessageBox.Show("当前营业日期:" + XTCSModel.GetXTCS.YYRQ + "\n夜审完成，系统将自动退出!");
                    Application.Exit();
                }
            }
        }
    }
}
